package tech.aistar.day01;

import java.sql.*;

/**
 * 本类用来演示: jdbc体验
 *
 * @author: success
 * @date: 2022/8/11 9:11 上午
 */
public class HelloWorld {
    public static void main(String[] args) {
        //1. 加载驱动 - 可以省略.
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            //2. 获取连接
            //准备连接参数
            String url = "jdbc:mysql://localhost:3306/dy?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC";
            String user = "root";
            String password = "root";

            conn = DriverManager.getConnection(url, user, password);

            //3. 创建语句对象 - 负责发送sql到db-serve端
            st = conn.createStatement();

            //4. 发送sql语句,准备一条sql语句
            String sql = "select id,first_name name,salary from s_emp";
            rs = st.executeQuery(sql);//传入dql语句.

            //5. 处理结果集
            while(rs.next()){//向下移动一行,如果下一行没有对应的行记录,直接返回false
                //列数据类型和java中的数据类型要对应好.

                //通过列的名称/列的序号(从1开始)
                Integer id = rs.getInt(1);

                //通过列的名称
                String name = rs.getString("name");

                double salary = rs.getDouble(3);

                System.out.printf("%d-%s-%.2f\n",id,name,salary);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //6. 释放资源,注意顺序,最后创建的资源需要先释放
            if(null!=rs){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(null!=st){
                try {
                    st.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(null!=conn){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
